﻿//author marcel

package ch.sfug.anim.transition
{
	import ch.sfug.anim.tween.property.Scaler;
	import ch.sfug.events.TweenEvent;
	
	import flash.display.Sprite;

	public class WipeTransition extends Transition
	{
		private var pt:Scaler;
		private var _ease:Function = null;
		private var _mask:Sprite;
		private var _maskInner:Sprite;
		private var _direction:String;
		
		public function WipeTransition(clip:Sprite=null, time:Number=1000, type:String = TransitionType.OUT, direction:String = DirectionType.LEFT_RIGHT)
		{ 
			super(clip, time, type);
			_direction = direction;
		}
		
		
		override protected function prepareForTransition():void 
		{
			super.prepareForTransition();
			
			createMask();
			
			pt = new Scaler(_mask, super.time);
			pt.addEventListener(TweenEvent.TWEEN_UPDATE, onTransitionUpdate);
			pt.addEventListener(TweenEvent.TWEEN_END, onTransitionEnd);
			
		}
		
		override public function startTransition():void 
		{
			prepareForTransition();
			onTransitionStart();
			
			if(type == "out")
			{
				if(_direction == DirectionType.LEFT_RIGHT)
				{
					pt.scaleFromXToX(1, 0, _ease);
				}
				else if(_direction == DirectionType.RIGHT_LEFT)
				{
					_mask.x 		+= _mask.width;
					pt.scaleFromXToX(-1, 0, _ease);
				}
				
			}
			else
			{
				if(_direction == DirectionType.LEFT_RIGHT)
				{
					pt.scaleFromXToX(0, 1, _ease);
				}
				else if(_direction == DirectionType.RIGHT_LEFT)
				{
					_mask.x 		+= _mask.width;
					pt.scaleFromXToX(0, -1, _ease);
				}
			}
		}
		
		override public function onTransitionEnd( event:TweenEvent ):void
		{			
			parentClip.mask = null;			
			cleanUp();
			dispatchEvent( event );
		}
		
		override public function stopTransition():void 
		{	
			if(pt != null)
			{
				pt.stop();
				pt.removeEventListener(TweenEvent.TWEEN_UPDATE, onTransitionUpdate);
				pt.removeEventListener(TweenEvent.TWEEN_END, onTransitionEnd);
				pt = null;
			}
			
			super.cleanUp();
		}
		
		private function createMask():void
		{
			_mask 		= new Sprite();
			_maskInner 	= new Sprite();
			_maskInner.graphics.beginFill(0xFF3300);
			_maskInner.graphics.drawRect( 0, 0, clip.width, clip.height );
			_maskInner.graphics.endFill();
			
			_mask.addChild( _maskInner );
			clip.addChild( _mask );
			parentClip.mask = _mask;
		}
		
		// getters and setters
		public function set ease( val:Function ):void
		{
			_ease = val;
		}
				
	}
}

